/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Data.FilmeDAO;
import Model.FilmeBean;
import View.acao.CadastrarFilme;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rafael
 */
public class CadastroFilme extends javax.swing.JInternalFrame {

    /**
     * Creates new form CadastroFilme
     */
    public CadastroFilme() {
        initComponents();
        preencherTabela("", 0);
    }
    private JTextField campo_a_preencher = null;

    public void setCampos(JTextField campo) {
        this.campo_a_preencher = campo;
        jTable1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() >= 2) {
                    //Objeto DAO para acessar dados do filme
                    FilmeDAO data = new FilmeDAO();
                    try {
                        //Pego o filme selecionado
                        FilmeBean filme = data.getFilme(Integer.parseInt(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()));

                        //Checa pela disponibilidade do Filme
                        if (data.isDisponivel(filme.getCodigo())) {
                            campo_a_preencher.setText(filme.getTitulo_portugues());
                            campo_a_preencher.setToolTipText(String.valueOf(filme.getCodigo()));
                            dispose();
                        } else {
                            JOptionPane.showMessageDialog(rootPane, "O filme selecionado não se encontra disponivel, por favor escolha outro");
                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(CadastroFilme.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            }
        });
    }

    private void preencherTabela(String parametro, int tipo_pesquisa) {

        //Instancio um objeto data para o filme
        FilmeDAO data = new FilmeDAO();
        Vector dados = null;
        Vector cabeçalho = new Vector();

        cabeçalho.addElement("Codigo");
        cabeçalho.addElement("Midia");
        cabeçalho.addElement("Valor");
        cabeçalho.addElement("Total De Midias");
        cabeçalho.addElement("Midias Disponiveis");
        cabeçalho.addElement("Valor adicional");
        cabeçalho.addElement("Titulo Portugues");
        cabeçalho.addElement("Titulo Original");
        cabeçalho.addElement("Genero");
        cabeçalho.addElement("Produtora");
        cabeçalho.addElement("Origem");
        cabeçalho.addElement("Ano");
        cabeçalho.addElement("Duração");
        cabeçalho.addElement("Diretor");
        cabeçalho.addElement("Elenco");

        try {
            //Pego a lista de filmes
            dados = data.listarFilme(parametro, tipo_pesquisa);
        } catch (SQLException ex) {
            Logger.getLogger(CadastroFilme.class.getName()).log(Level.SEVERE, null, ex);
        }

        //Declaro o modelo da tabela
        DefaultTableModel modelo = new DefaultTableModel(dados, cabeçalho) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        jTable1.setModel(modelo);

        //Arrumar a tabela
        int[] valores = {75, 99, 61, 100, 125, 97, 292, 318, 156, 142, 150, 75, 125, 169, 472};
        for (int i = 0; i < jTable1.getColumnModel().getColumnCount(); i++) {
            jTable1.getColumnModel().getColumn(i).setPreferredWidth(valores[i]);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Cadastro de Filmes");
        setToolTipText("");

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setFillsViewportHeight(true);
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Pesquisa: ");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Codigo", "Titulo Portugues", "Titulo Original", "Produtora", "Diretor", "Elenco" }));

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 553, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 170, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(0, 143, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Editar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Excluir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jButton3)
                .add(18, 18, 18)
                .add(jButton1)
                .add(18, 18, 18)
                .add(jButton2)
                .addContainerGap())
        );

        layout.linkSize(new java.awt.Component[] {jButton1, jButton2}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton2)
                    .add(jButton3)
                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        CadastrarFilme cf = new CadastrarFilme(null);
        if (!cf.isFail()) {
            TelaPrincipal.adicionarInternalFrame(new CadastrarFilme(null));
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        preencherTabela(jTextField1.getText(), jComboBox1.getSelectedIndex());
    }//GEN-LAST:event_jTextField1KeyReleased

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (jTable1.getSelectedRow() != -1) {
            FilmeDAO data = new FilmeDAO();
            try {
                TelaPrincipal.adicionarInternalFrame(new CadastrarFilme(data.getFilme(Integer.parseInt(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()))));
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(rootPane, "Erro: \n" + ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primeiro selecione um registro");
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        if (jTable1.getSelectedRow() != -1) {
            FilmeDAO data = new FilmeDAO();
            try {
                if (data.deletarFilme(Integer.parseInt(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()))) {
                    JOptionPane.showMessageDialog(rootPane, "Deletado com sucesso!");
                } else {
                    throw new SQLException("Erro ao deletar filme");
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(rootPane, "Erro: \n" + ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primeiro selecione um registro");
        }
    }//GEN-LAST:event_jButton3ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
